package javaapplication1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class TCPListener extends Thread {

    TCPListener(String ipAddress, int port, String resourceId, Klient instance) {
        this.klientInstance = instance;
        this.ipAddress = ipAddress;
        this.port = port;
        this.resourceId = resourceId;
        //this.metric = metric;
    }

    @Override
    public void run() {
        if (connectToServer(ipAddress, port)) {
            //infinite loop
            while (work) {
                try {
                    if ((data = in.readLine()) == null) {//blocked here, waits for new line from server
                        work = false;
                        klientInstance.printLog("Monitor ended the connection");
                        stopWork();
                    } else {//if got new line - reads it and prints out for user
                        klientInstance.printData(resourceId+": "+data);
                    }
                } catch (IOException ex) {
                    klientInstance.printLog("Error: Monitor ended the connection");
                    work = false;
                }
            }
        } else {
            klientInstance.printLog("\n***Error: could not connect to the TCP socket\n");
        };
    }

    void stopWork() {
        work = false;
    }

    private boolean connectToServer(String ipAddress, int port) {
        try {
            clientSocket = new Socket(ipAddress, port);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    
    Klient klientInstance;
    BufferedReader in;
    Socket clientSocket;
    boolean work = true;
    String ipAddress;
    int port;
    String resourceId;
    //String metric;
    String data = "[here will show the data]";
}
